package controllers

import "LoginTemplate/models"

type ArticleController struct {
	BaseController
}

type Article struct {
	ID          int    `json:"id"`
	ArticleName string `json:"article_name"`
	ArticleType int    `json:"article_type"`
	IsDe        int    `json:"is_de"`
}

// 添加文章
func (u *ArticleController) InsertArticle() {
	var article Article
	err := u.ShouldBind(&article)
	if err != nil {
		println(err.Error())
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	sql := "insert into article ( article_name,article_type ) values ( ? , ? )"
	tx := models.DB.Debug().Exec(sql, article.ArticleName, article.ArticleType)
	if tx.Error != nil {
		u.JsonMsg(500, "", "失败")
	}
	u.JsonMsg(200, "", "成功")
}

// 修改文章
func (u *ArticleController) UpdateArticle() {
	var article Article
	err := u.ShouldBind(&article)
	if err != nil {
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	sql := "update article set article_name = ?,article_type = ?,is_de = ? where id = ?"
	tx := models.DB.Debug().Exec(sql, article.ArticleName, article.ArticleType, article.IsDe, article.ID)
	if tx.Error != nil {
		u.JsonMsg(500, "", "失败")
	}
	u.JsonMsg(200, "", "成功")
}

type ArticleData struct {
	Code        int       `json:"code"`
	Msg         string    `json:"msg"`
	Data        []Article `json:"data"`
	Sum         int       `json:"sum"`         //总页数
	CurrentPage int       `json:"currentPage"` //当前页
	TotalNumber int       `json:"totalNumber"` //总条数
}

// 查询文章
func (u *ArticleController) SelectArticle() {
	var pictureList PictureList
	err := u.ShouldBind(&pictureList)
	var sum int
	var totalNumber int
	if err != nil {
		println(err.Error())
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	var article []Article
	sql := "select * from article where is_de = 0 limit ? , ?"
	tx := models.DB.Debug().Raw(sql, (pictureList.Page-1)*pictureList.Size, pictureList.Size).Scan(&article)
	sqlsum := "SELECT CEIL(COUNT(*) / ? ) FROM article where is_de = 0"
	models.DB.Debug().Raw(sqlsum, pictureList.Size).Scan(&sum)
	sqlNumBer := "select count(*) from article where is_de = 0"
	models.DB.Debug().Raw(sqlNumBer).Scan(&totalNumber)
	if tx.Error != nil {
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	var picturedata ArticleData
	picturedata.Code = 200
	picturedata.Data = article
	picturedata.Msg = "成功"
	picturedata.Sum = sum
	picturedata.CurrentPage = pictureList.Page
	picturedata.TotalNumber = totalNumber
	u.JsonMsg(200, map[string]interface{}{
		"list":  picturedata,
		"count": "",
	}, "success")
}
